package com.shyroke.daydayzhuansvc.service.impl;

import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.dto.NewsDto;
import com.shyroke.daydayzhuanapi.dto.UserMain;
import com.shyroke.daydayzhuanapi.entity.NewsEntity;
import com.shyroke.daydayzhuanapi.entity.QNewsEntity;
import com.shyroke.daydayzhuanapi.mapper.NewsMapper;
import com.shyroke.daydayzhuandao.respository.NewsRepository;
import com.shyroke.daydayzhuansvc.service.INewsService;
import com.shyroke.daydayzhuansvc.util.Page;
import com.shyroke.daydayzhuansvc.util.TabelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类名 ：
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2019/1/14 10:31
 */
@Service
public class NewsService implements INewsService {
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private JPAQueryFactory factory;
    @Autowired
    private NewsRepository newsRepository;

    @Override
    public TabelData<NewsDto> getTableDate(Page page, Integer isRead, UserMain user) {
        QNewsEntity qNewsEntity = QNewsEntity.newsEntity;
        JPAQuery<NewsEntity> query = factory.selectFrom(qNewsEntity);

        if(isRead != null){
            query = query.where(qNewsEntity.isRead.eq(isRead));
        }
        if(user != null && user.getId() != null){
            query = query.where(qNewsEntity.userId.eq(user.getId()));
        }
        QueryResults<NewsEntity> queryResults = query
                .offset(PageRequest.of(page.getPage() - 1, page.getLimit()).getOffset()).limit(page.getLimit())
                .orderBy(qNewsEntity.id.desc())
                .fetchResults();

        List<NewsDto> list = queryResults.getResults().stream().map(e -> newsMapper.entityToDto(e)).collect(Collectors.toList());

        return new TabelData(list,(int)queryResults.getTotal());
    }

    @Override
    public void readNews(Integer id) {
        Optional<NewsEntity> optionalNewsEntity = newsRepository.findById(id);
        if(optionalNewsEntity.isPresent()){
            NewsEntity newsEntity = optionalNewsEntity.get();
            newsEntity.setIsRead(1);
            newsRepository.save(newsEntity);
        }
    }
}
